//


#import "NT_EditNoteViewController.h"
#import "NT_MenuTableVew.h"

@interface NT_EditNoteViewController ()<UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
/** button*/
@property (nonatomic, strong) UIButton *selectBtn;
/** jiantou*/
@property (nonatomic, strong) UIImageView *img;
/** shijian*/
@property (nonatomic, strong) UILabel *dateLabel;
/** */
@property (nonatomic, strong) UITextView *textView;
/** */
@property (nonatomic, strong) UILabel *placeholderLabel; // 输入框提示语句
/** 时间*/
@property (nonatomic, copy) NSString *dateStr;
/** btn*/
@property (nonatomic, copy) NSString *btnStr;
/** */
@property (nonatomic, strong) NT_CoreDataBase *data;
/** 照片*/
@property (nonatomic, strong) UIImageView *selectImageView;
/** 删除*/
@property (nonatomic, strong) UIButton *deleteButton;

@end

@implementation NT_EditNoteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self setnavBatTitle:@"Please add content and return"];
    
    _data = [[NT_CoreDataBase alloc]initWithCoreData:@"Note" modelName:@"NoteData" success:^{} fail:^(NSError * _Nullable error) {}];
    //
    __weak typeof(self) weakSelf = self;
    [self nt_setupLeftAndRightwrurSetting:@"Save" block:^{
        [weakSelf saveSSSSSS];
    }];
    //
    [self createView];
    
}
//
- (void)actionBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}
//
- (void)createView {
    //
    self.selectBtn = ({
        _btnStr = @"travel";
        UIButton *button = [[UIButton alloc]init];
        [button setTitle:_btnStr forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button.titleLabel setFont:FontPFRegular(kRelativeWidth(15))];
        [button setImage:[UIImage imageNamed:@"travel3"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(Action) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        button;
    });
    [self.selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(UI_NAV_BAR_HEIGHT + kRelativeHeight(20));
        make.left.mas_offset(kRelativeWidth(30));
        make.height.mas_equalTo(kRelativeHeight(30));
    }];
    //
    self.img =  ({
        UIImageView *img = [[UIImageView alloc]init];
        img.image = [UIImage imageNamed:@"arrow_down1"];
        [self.view addSubview:img];
        img;
    });
    [self.img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.selectBtn);
        make.left.mas_equalTo(self.selectBtn.mas_right).offset(5);
        make.width.height.mas_equalTo(kRelativeWidth(20));
    }];
    self.dateLabel = ({
        //当前时间
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        _dateStr = [formatter stringFromDate:[NSDate date]];
        
        UILabel *label = [[UILabel alloc]init];
        label.textColor = rgba(90, 90, 90, 1);
        label.font = FontPFRegular(kRelativeWidth(15));
        label.text = _dateStr;
        [self.view addSubview:label];
        label;
    });
    [self.dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.selectBtn);
        make.right.mas_offset(-kRelativeWidth(20));
        make.height.mas_equalTo(kRelativeHeight(20));
    }];
    
    //
    _textView = ({
        UITextView *textView = [[UITextView alloc]init];
        textView.font = FontPFRegular(kRelativeWidth(14));
        textView.backgroundColor = RGB(255, 255, 255);
        textView.textColor = rgba(51, 51, 51, 1);
        textView.delegate  = self;
        textView.text = _model.title;
        [self.view addSubview:textView];
        textView;
    });
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.selectBtn.mas_bottom).offset(10);
        make.left.mas_equalTo(self.selectBtn);
        make.right.mas_offset(-kRelativeWidth(30));
        make.height.mas_equalTo(kRelativeHeight(220));
    }];
    // 假文字placeholder
    _placeholderLabel = ({
        UILabel *label = [[UILabel alloc]init];
        label.textColor = rgba(187, 187, 187, 1);
        label.font = FontPFRegular(kRelativeWidth(14));
        label.text = _model != nil ? @"" : @"Input a content...";
        [_textView addSubview:label];
        label;
    });
    [_placeholderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(2);
        make.left.mas_offset(2);
        make.height.mas_equalTo(kRelativeHeight(30));
    }];
    
    [self.view addSubview:self.selectImageView];
    [self.selectImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.textView.mas_bottom).offset(kRelativeHeight(10));
        make.width.mas_equalTo(kRelativeWidth(80));
        make.left.mas_equalTo(self.textView);
        make.height.mas_equalTo(kRelativeHeight(80));
    }];
    [self.selectImageView addSubview:self.deleteButton];
    [self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.right.mas_offset(0);
        make.width.height.mas_equalTo(kRelativeWidth(25));
    }];
}
//
- (UIImageView *)selectImageView {
    if (!_selectImageView) {
        _selectImageView = [[UIImageView alloc] init];
        _selectImageView.contentMode = UIViewContentModeScaleAspectFill;
        _selectImageView.clipsToBounds = YES;
        _selectImageView.image = (UIImage*)_model.img;
        _selectImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectImage)];
        [_selectImageView addGestureRecognizer:gesture];
    }
    
    return _selectImageView;
}


- (UIButton *)deleteButton {
    if (!_deleteButton) {
        _deleteButton = [[UIButton alloc] init];
        [_deleteButton setImage:[UIImage imageNamed:@"ImageError"] forState:UIControlStateNormal];
        [_deleteButton addTarget:self action:@selector(deleteImage) forControlEvents:UIControlEventTouchUpInside];
        _deleteButton.hidden = YES;
    }
    
    return _deleteButton;
}
//
- (void)deleteImage
{
    self.selectImageView.image = [UIImage imageNamed:@"ic_tupian"];
    self.deleteButton.hidden = YES;
}
//
- (void)selectImage
{
    if (!self.deleteButton.hidden) {
        return;
    }
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {   //打开相册
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate= self;
        picker.allowsEditing = YES;
        picker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

//  相册 代理
- (void)imagePickerController:(UIImagePickerController *)picker                     //返回picker选中的图片
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    self.deleteButton.hidden = NO;
    _selectImageView.image=newPhoto;    //设置为头像图片
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

//
- (void)Action {
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"isFirst"]) {
        return;
    }
    NT_MenuTableVew *vc = [[NT_MenuTableVew alloc]init];
    [vc showV];
    //
    __weak typeof(self) weakSelf = self;
    vc.dataBlock = ^(NSString * _Nonnull text, UIImage * _Nonnull img) {
        weakSelf.btnStr = text;
        [weakSelf.selectBtn setTitle:text forState:UIControlStateNormal];
        [weakSelf.selectBtn setImage:img forState:UIControlStateNormal];
    };
}
-(void)textViewDidChange:(UITextView *)textView{
    //清空内容
    _placeholderLabel.text = @"";
    if (_textView.text.length == 0) {
        _placeholderLabel.text = @"Input a content...";
    }
    if ([textView.text length] > 200) {
        textView.text = [textView.text substringWithRange:NSMakeRange(0, 200)];
        [textView.undoManager removeAllActions];
        [textView becomeFirstResponder];
        return;
    }
}
//MARK:
- (void)saveSSSSSS{
    if (_textView.text.length <= 0 ) {
        return;
    }
    if ([_selectImageView.image isEqual:[UIImage imageNamed:@"ic_tupian"]]) {
        _selectImageView.image = [UIImage imageNamed:@"header33"];
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary new];
    
    [dic setObject:_textView.text forKey:@"title"];
    [dic setObject:_btnStr forKey:@"category"];
    [dic setObject:_selectImageView.image forKey:@"img"];
    [dic setObject:_dateStr forKey:@"date"];
    
    [_data ntUpdateEntity:dic key:[NSString stringWithFormat:@"id=%@",_model.id] success:^{
        [self dismissViewControllerAnimated:YES completion:nil];
        
    } fail:^(NSError * _Nullable error) {}];
    
    
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (NSString *)randomhhhhhhhhhh
{
    const int count =6;
    NSString * sourceString=@"678912345";
    NSMutableString *rehhhh=[[NSMutableString alloc]init];
    for (int i = 0; i < count; i++) {
        unsigned index=rand()%[sourceString length];
        NSString * s=[sourceString substringWithRange:NSMakeRange(index, 1)];
        [rehhhh appendString:s];
    }
    return rehhhh;
}


@end
